package com.saltedfish.tool.dialog;

import android.app.Activity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.haibin.calendarview.CalendarUtil;
import com.haibin.calendarview.CalendarView;
import com.haibin.calendarview.Calendars;
import com.saltedfish.tool.R;
import com.saltedfish.tool.model.SmallTable;
import com.saltedfish.tool.ui.flag.adapter.SelectDayAdapter;
import com.saltedfish.tool.util.DateUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.base.SimpleListener;
import cn.droidlover.xdroidmvp.log.XLog;
import cn.droidlover.xdroidmvp.popwindow.DialogHelper;
import cn.droidlover.xdroidmvp.util.ToastUtils;

public class UIDateEndDialog extends DialogHelper implements
        CalendarView.OnCalendarInterceptListener,
        CalendarView.OnCalendarSelectListener,
        CalendarView.OnMonthChangeListener {

    @BindView(R.id.tv_calender_month)
    TextView tv_calender_month;
    @BindView(R.id.calenderMonth)
    LinearLayout calenderMonth;
    @BindView(R.id.tvBack)
    ImageView tvBack;
    @BindView(R.id.tvDateTitle)
    TextView tvDateTitle;
    @BindView(R.id.calendarView)
    CalendarView mCalendarView;

    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.linear_date_end)
    LinearLayout linear_date_end;

    Date curDate;

    Calendar cal;


    SimpleDateFormat formatter ;

    //选中时间
    private String putDate;
    //当天时间
    private String dayDate;
    private SelectDayAdapter flagAdapter;
    private SmallTable subFlagModel;
    private int year;
    private int month;
    private int day;

    public UIDateEndDialog(Activity context) {
        super(context, R.style.AlertDialogStyle);
        this.mContext = context;
        setFullWidthScreen();
        setGravity(Gravity.BOTTOM);
        setAnimSet(R.style.popRightPopAnim);

    }

    private Calendars getSchemeCalendar(int year, int month, int day, int color, String text,Boolean flag) {
        Calendars calendar = new Calendars();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setCheck(flag);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
      //  calendar.setSolarTerm(text);
        return calendar;
    }



    @Override
    protected int getLayoutId() {
        return R.layout.dialog_ui_date_end;
    }


    public void updateDate( SmallTable subFlagModel) {
        this.subFlagModel = subFlagModel;
        year = CalendarUtil.getDate("yyyy", DateUtils.strToDate(subFlagModel.startTime));
        month = CalendarUtil.getDate("MM", DateUtils.strToDate(subFlagModel.startTime));
        day = CalendarUtil.getDate("dd", DateUtils.strToDate(subFlagModel.startTime));

            linear_date_end.setVisibility(View.VISIBLE);
            tvDateTitle.setText("结束日期");
            initData();
            if(!TextUtils.isEmpty(subFlagModel.endTime)){
                putDate = subFlagModel.endTime;
               // putDate = formatterDay.format(subFlagModel.endTime);
               // String date = formatter.format(subFlagModel.endTime);
                int endYear = CalendarUtil.getDate("yyyy", DateUtils.strToDate(subFlagModel.endTime));
                int  endMonth = CalendarUtil.getDate("MM", DateUtils.strToDate(subFlagModel.endTime));
                int  endDay = CalendarUtil.getDate("dd", DateUtils.strToDate(subFlagModel.endTime));
                String endTime = DateUtils.strToDateStr2(subFlagModel.endTime);
                Map<String, Calendars> map = new HashMap<>();

                map.put(getSchemeCalendar(year, month, day, 0xFF489dff, "开始",false).toString(),
                        getSchemeCalendar(year, month, day, 0xFF489dff, "开始",false));
                map.put(getSchemeCalendar(endYear, endMonth, endDay, 0xFF489dff, "显示",true).toString(),
                        getSchemeCalendar(endYear, endMonth, endDay, 0xFF489dff, "显示",true));
                //此方法在巨大的数据量上不影响遍历性能，推荐使用
                mCalendarView.setSchemeDate(map);
                initShowDateView(endTime);

            }else {
                this.putDate = "";
            }

    }


    @Override
    protected void initView() {
        cal = Calendar.getInstance();
        formatter = new SimpleDateFormat("yyyy年MM月");
        //获取当前时间
        curDate = cal.getTime();
        String strDate = formatter.format(curDate);

        if (!TextUtils.isEmpty(strDate)) {
            tv_calender_month.setText(strDate);
        }

        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

        calenderMonth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initMonthView();
            }
        });

        //设置日期拦截事件，当前有效
        mCalendarView.setOnCalendarInterceptListener(this);
        mCalendarView.setOnCalendarSelectListener(this);
        mCalendarView.setOnMonthChangeListener(this);

    }



    private  UIMonthDialog uiMonthDialog ;

    private void initMonthView() {
         String month = tv_calender_month.getText().toString();
        if(uiMonthDialog == null){
            uiMonthDialog = new UIMonthDialog(mContext);
            uiMonthDialog.setSimpleListener(new SimpleListener() {
                @Override
                public void onClick(String strDate) {
                    initShowDateView(strDate);
                }

            });
        }
        uiMonthDialog.updateDate(month);
        uiMonthDialog.show();

    }


    /**
     * 日期界面展示
     */
    private void initShowDateView(String strDate) {
        tv_calender_month.setText(strDate);
        try {
            Date newTime = formatter.parse(strDate);
            mCalendarView.setDelegatemMonthChange(newTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    List<Integer> selectList;

    private int selectPosition = 10;



    /**
     * 初始化常用天数
     */
    @Override
    protected void initData() {
            selectPosition = 10;
            selectList = new ArrayList<>();
            selectList.add(7);
            selectList.add(30);
            selectList.add(100);
            selectList.add(365);
            selectList.add(500);
            selectList.add(1000);

            flagAdapter = new SelectDayAdapter(selectList,mContext);
            flagAdapter.setListener(new SimpleListener() {

                @Override
                public void onClick(int index) {
                    selectPosition = index;
                    putDate = DateUtils.getNextDay(subFlagModel.startTime,selectList.get(index)-1);
                    String date = DateUtils.strToDateStr2(putDate);
                    Map<String, Calendars> map = new HashMap<>();
                    //清除标记
                    mCalendarView.clearSchemeDate();
                    //清除单选
                    mCalendarView.clearSingleSelect();
                    int endYear = CalendarUtil.getDate("yyyy", DateUtils.strToDate(putDate));
                    int  endMonth = CalendarUtil.getDate("MM", DateUtils.strToDate(putDate));
                    int  endDay = CalendarUtil.getDate("dd", DateUtils.strToDate(putDate));
                    map.put(getSchemeCalendar(year, month, day, 0xFF489dff, "开始",false).toString(),
                            getSchemeCalendar(year, month, day, 0xFF489dff, "开始",false));
                    map.put(getSchemeCalendar(endYear, endMonth, endDay, 0xFF489dff, "显示",true).toString(),
                            getSchemeCalendar(endYear, endMonth, endDay, 0xFF489dff, "显示",true));
                    //此方法在巨大的数据量上不影响遍历性能，推荐使用
                    mCalendarView.setSchemeDate(map);
                    initShowDateView(date);
                }
            });
            flagAdapter.setSelectPosition(selectPosition);
            mRecyclerView.setHasFixedSize(true);
            mRecyclerView.setLayoutManager(new GridLayoutManager(mContext,3));
            mRecyclerView.setAdapter(flagAdapter);
    }


    @Override
    protected void dialogDismiss() {
        dismiss();
    }

    @Override
    public void dismiss() {

        subFlagModel.endTime = putDate;
        if (listener != null) {
            listener.onDateClick(subFlagModel);
        }

        mContext.getWindow().setStatusBarColor(mContext.getResources().getColor(R.color.color_white));
        initView();
        initData();
        super.dismiss();

    }

    private SimpleDateListener listener;

    /**
     * 屏蔽某些不可点击的日期，可根据自己的业务自行修改
     * 如 calendar > 2018年1月1日 && calendar <= 2020年12月31日
     *
     * @param calendar calendar
     * @return 是否屏蔽某些不可点击的日期，MonthView和WeekView有类似的API可调用
     */
    @Override
    public boolean onCalendarIntercept(Calendars calendar) {
//        String day = "" + calendar.getYear() + "年" + calendar.getMonth() +  "月" + calendar.getDay() + "日" ;
//        String curDay = "" + mCalendarView.getCurYear() + "年" + mCalendarView.getCurMonth() + "月" + mCalendarView.getCurDay() + "日" ;
//        int indexDay = DateUtils.compareEqualsDate(day, curDay);
 //       int day = calendar.getDay();
        return calendar.getTimeInMillis() < getSelectTimeInMillis() ;

    }

    private long getCurrentDayMill(){
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.set(java.util.Calendar.HOUR,0);
        calendar.set(java.util.Calendar.MINUTE,0);
        calendar.set(java.util.Calendar.MILLISECOND,0);
        return calendar.getTimeInMillis();
    }

    public long getSelectTimeInMillis() {
        XLog.e("-----------"+year+"-"+month+"-"+day);
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.set(java.util.Calendar.YEAR, year);
        calendar.set(java.util.Calendar.MONTH, month - 1);
        calendar.set(java.util.Calendar.DAY_OF_MONTH, day);
        return calendar.getTimeInMillis();
    }

    @Override
    public void onCalendarInterceptClick(Calendars calendar, boolean isClick) {
        Log.e(isClick+"---2-->>",""+calendar.getDay());
        if(isClick){
            ToastUtils.showMessage(mContext,"请选择开始日期之后的日期");

//            if(calendar.getTimeInMillis() < getSelectTimeInMillis()){
//            }
        }
    }

    @Override
    public void onCalendarOutOfRange(Calendars calendar) {
    }

    @Override
    public void onCalendarSelect(Calendars calendar, boolean isClick) {
        if(isClick){
            String defaultStartDate =calendar.getYear() + "-"+ calendar.getMonth() + "-" + calendar.getDay() ;
            putDate = defaultStartDate;
            initData();
            mCalendarView.clearSchemeDate();
            Map<String, Calendars> map = new HashMap<>();
            map.put(getSchemeCalendar(year, month, day, 0xFF489dff, "开始",false).toString(),
                    getSchemeCalendar(year, month, day, 0xFF489dff, "开始",false));
            //此方法在巨大的数据量上不影响遍历性能，推荐使用
            mCalendarView.setSchemeDate(map);
        }

    }


    @Override
    public void onMonthChange(int year, int month) {
        String months = "";
        if(month <10){
            months = "0" + month;
        }else {
            months = String.valueOf(month);
        }
        String day = year + "年" + months + "月";
        Log.e("---2-->>",""+day);
        if (!TextUtils.isEmpty(day)) {
            tv_calender_month.setText(day);
        }
    }

    public static class SimpleDateListener{
        void onDateClick(SmallTable subFlagModel) { }
    }

    public void setListener(SimpleDateListener listener) {
        this.listener = listener;
    }
}
